import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    // 如果后端返回的是包装格式 {success, message, data}
    if (response.data && typeof response.data === 'object' && 'success' in response.data) {
      if (response.data.success) {
        return response.data.data;
      } else {
        return Promise.reject(new Error(response.data.message || '请求失败'));
      }
    }
    // 否则直接返回数据
    return response.data;
  },
  (error) => {
    console.error('API Error:', error);
    return Promise.reject(error);
  }
);

// ==================== 商品相关API ====================
export const productAPI = {
  // 获取所有商品（分页）
  getAll: (page = 0, size = 10) => 
    apiClient.get('/admin/products', { params: { page, size } }),
  
  // 根据ID获取商品 - 修复路径
  getById: (id, userId) => 
    apiClient.get(`/client/products/${id}`, { params: { userId } }),
  
  // 搜索商品 - 修复路径和参数
  search: (keyword, userId) => 
    apiClient.get('/client/products/search', { params: { keyword, userId } }),
  
  // 创建商品
  create: (product) => 
    apiClient.post('/admin/products', product),
  
  // 更新商品
  update: (id, product) => 
    apiClient.put(`/admin/products/${id}`, product),
  
  // 删除商品
  delete: (id) => 
    apiClient.delete(`/admin/products/${id}`),
  
  // 获取商品统计
  getStats: () => 
    apiClient.get('/admin/products/stats'),
  
  // 记录商品点击
  recordClick: (id, userId) => 
    apiClient.post(`/client/products/${id}/click`, null, { params: { userId } }),
};

// ==================== 用户相关API ====================
export const userAPI = {
  // 获取所有用户（分页）
  getAll: (page = 0, size = 10) => 
    apiClient.get('/admin/users', { params: { page, size } }),
  
  // 根据ID获取用户
  getById: (id) => 
    apiClient.get(`/admin/users/${id}`),
  
  // 创建用户
  create: (user) => 
    apiClient.post('/admin/users', user),
  
  // 更新用户
  update: (id, user) => 
    apiClient.put(`/admin/users/${id}`, user),
  
  // 删除用户
  delete: (id) => 
    apiClient.delete(`/admin/users/${id}`),
  
  // 获取用户统计
  getStats: () => 
    apiClient.get('/admin/users/stats'),
  
  // 搜索用户 - 修复路径
  search: (keyword) => 
    apiClient.get('/client/users/search', { params: { keyword } }),
};

// ==================== 订单相关API ====================
export const orderAPI = {
  // 获取所有订单（分页）
  getAll: (page = 0, size = 10) => 
    apiClient.get('/admin/orders', { params: { page, size } }),
  
  // 根据ID获取订单
  getById: (id) => 
    apiClient.get(`/admin/orders/${id}`),
  
  // 创建订单
  create: (userId, orderItems) => 
    apiClient.post('/client/orders', orderItems, { params: { userId } }),
  
  // 更新订单状态
  updateStatus: (id, status) => 
    apiClient.put(`/admin/orders/${id}/status`, null, { params: { status } }),
  
  // 支付订单 - 修复路径
  pay: (id) => 
    apiClient.post(`/client/orders/${id}/pay`),
  
  // 获取订单状态选项 - 修复路径
  getStatusOptions: () => 
    apiClient.get('/client/orders/status-options'),
  
  // 取消订单
  cancel: (id) => 
    apiClient.post(`/client/orders/${id}/cancel`),
  
  // 删除订单
  delete: (id) => 
    apiClient.delete(`/admin/orders/${id}`),
  
  // 获取用户订单
  getUserOrders: (userId, page = 0, size = 10) => 
    apiClient.get(`/client/orders/user/${userId}`, { params: { page, size } }),
  
  // 获取订单统计
  getStats: () => 
    apiClient.get('/admin/orders/stats'),
  
  // 获取订单状态选项
  getStatusOptions: () => 
    apiClient.get('/admin/orders/status-options'),
  
  // 根据时间范围获取订单
  getByDateRange: (startDate, endDate) => 
    apiClient.get('/admin/orders/date-range', { params: { startDate, endDate } }),
};

// ==================== 分析相关API ====================
export const analyticsAPI = {
  // 记录用户行为
  recordBehavior: (userId, eventType, productId, category, searchKeyword) => 
    apiClient.post('/analytics/behavior', null, {
      params: { userId, eventType, productId, category, searchKeyword }
    }),
  
  // 记录商品浏览
  recordProductView: (userId, productId, category) => 
    apiClient.post('/analytics/product-view', null, {
      params: { userId, productId, category }
    }),
  
  // 记录搜索行为
  recordSearch: (userId, keyword, resultCount) => 
    apiClient.post('/analytics/search', null, {
      params: { userId, keyword, resultCount }
    }),
  
  // 记录加购行为
  recordAddToCart: (userId, productId, category) => 
    apiClient.post('/analytics/add-cart', null, {
      params: { userId, productId, category }
    }),
  
  // 获取热门商品
  getHotProducts: (limit = 10) => 
    apiClient.get('/analytics/hot-products', { params: { limit } }),
  
  // 获取用户画像
  getUserProfile: (userId) => 
    apiClient.get(`/analytics/user-profile/${userId}`),
  
  // 获取搜索统计
  getSearchStats: (startDate, endDate) => 
    apiClient.get('/analytics/search-stats', { params: { startDate, endDate } }),
  
  // 获取用户行为日志
  getBehaviorLogs: (userId, page = 0, size = 10) => 
    apiClient.get('/analytics/behavior-logs', { params: { userId, page, size } }),
};

// ==================== 兼容旧版本API ====================
export const searchProducts = (keyword) => productAPI.search(keyword);
export const getAllProducts = () => productAPI.getAll();
export const getProductById = (id) => productAPI.getById(id);
export const addProduct = (product) => productAPI.create(product);

export default apiClient;